package com.lagou.edu.mvcframework.servlet;

import com.lagou.edu.mvcframework.annotations.*;
import com.lagou.edu.mvcframework.pojo.Handler;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Title: mvc
 * @Description:
 * @Author: Wenfeng Cheng
 * @Date: 2021-01-18 14:03
 * @Version: 1.0.0
 */
public class LgDispatcherServlet extends HttpServlet {

    //保存配置文件
    private Properties properties = new Properties();

    //保存扫描到的类的全限定名
    private List<String> classNames = new ArrayList<>();

    //ioc容器
    private Map<String,Object> ioc = new HashMap<>();

    //handlerMapping
    private List<Handler> handlerMapping = new ArrayList<>();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取handler
        Handler handler = getHandler(req);
        if(handler == null){
            resp.getWriter().write("404 not found");
            return;
        }
        //参数绑定
        //1、获取handler方法参数类型数组
        Class<?>[] parameterTypes = handler.getMethod().getParameterTypes();
        //2、创建参数数组
        Object[] paraValues = new Object[parameterTypes.length];
        Map<String, String[]> parameterMap = req.getParameterMap();
        for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
            String join = StringUtils.join(entry.getValue(), ",");
            if(!handler.getParamIndexMapping().containsKey(entry.getKey())){
                continue;
            }
            Integer index = handler.getParamIndexMapping().get(entry.getKey());
            paraValues[index] = join;
        }
        Integer httpServletRequestIndex = handler.getParamIndexMapping().get(HttpServletRequest.class.getSimpleName());
        paraValues[httpServletRequestIndex] = req;
        Integer httpServletResponseIndex = handler.getParamIndexMapping().get(HttpServletResponse.class.getSimpleName());
        paraValues[httpServletResponseIndex] = resp;

        Class<?> aClass = handler.getController().getClass();
        Method method = handler.getMethod();
        String[] usernames = parameterMap.get("username");
        //权限判定
        if(aClass.isAnnotationPresent(Security.class)){
            Security securityAnno = aClass.getAnnotation(Security.class);
            if(!isSecurity(securityAnno, usernames)){
                resp.getWriter().write("No access rights");
                return;
            }
        }
        if(method.isAnnotationPresent(Security.class)){
            Security securityAnno = method.getAnnotation(Security.class);
            if(!isSecurity(securityAnno, usernames)){
                resp.getWriter().write("No access rights");
                return;
            }
        }
        try {
            Object result = handler.getMethod().invoke(handler.getController(), paraValues);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    /**
     * 权限判定
     * @param securityAnno
     * @param usernames
     * @return
     */
    private boolean isSecurity(Security securityAnno, String[] usernames){
        String[] value = securityAnno.value();
        if(value.length == 0){
            return true;
        }
        if(usernames == null || usernames.length == 0){
            return false;
        }
        for (int i = 0; i < usernames.length; i++) {
            for (int j = 0; j < value.length; j++) {
                if(StringUtils.equals(usernames[i],value[j])){
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 获取handler
     * @param req
     * @return
     */
    private Handler getHandler(HttpServletRequest req) {
        if(handlerMapping.isEmpty()){
            return null;
        }
        String url = req.getRequestURI();
        for (Handler handler : handlerMapping) {
            Matcher matcher = handler.getPattern().matcher(url);
            if(!matcher.matches()){
                continue;
            }
            return handler;
        }
        return null;
    }

    @Override
    public void init(ServletConfig config) throws ServletException {
        //1、加载配置文件
        String contextConfigLocation = config.getInitParameter("contextConfigLocation");
        doLoadConfig(contextConfigLocation);
        //2、扫描类和注解
        doScan(properties.getProperty("scanPackage"));
        //3、实例化Bean
        doInstance();
        //4、依赖注入
        doAutowired();
        //5、维护url与handle的对应关系
        initHandleMapping();
        System.out.println("lagou mvc 初始化完成....");
        //等待请求
    }

    /**
     * 维护url与handle的关系
     */
    private void initHandleMapping() {
        if(ioc.isEmpty()){
            return;
        }
        for (Map.Entry<String, Object> entry : ioc.entrySet()) {
            Object value = entry.getValue();
            Class<?> aClass = value.getClass();
            if(!aClass.isAnnotationPresent(LagouController.class)){
                continue;
            }
            String baseUrl = "";
            if(aClass.isAnnotationPresent(LagouRequestMapping.class)){
                LagouRequestMapping annotation = aClass.getAnnotation(LagouRequestMapping.class);
                baseUrl = annotation.value();
            }
            Method[] methods = aClass.getMethods();
            for (Method method : methods) {
                if(!method.isAnnotationPresent(LagouRequestMapping.class)){
                    continue;
                }
                LagouRequestMapping annotation = method.getAnnotation(LagouRequestMapping.class);
                String methodUrl = annotation.value();
                String url = baseUrl + methodUrl;
                Handler handler = new Handler(value, method, Pattern.compile(url));
                //计算参数位置
                Parameter[] parameters = method.getParameters();
                for (int i=0; i < parameters.length; i++) {
                    Parameter parameter = parameters[i];
                    if(parameter.getType() == HttpServletRequest.class || parameter.getType() == HttpServletResponse.class){
                        handler.getParamIndexMapping().put(parameter.getType().getSimpleName(), i);
                    }else{
                        handler.getParamIndexMapping().put(parameter.getName(), i);
                    }
                }
                handlerMapping.add(handler);
            }
        }
    }

    /**
     * 依赖注入
     */
    private void doAutowired() {
        if(ioc.isEmpty()){
            return;
        }
        for (Map.Entry<String, Object> stringObjectEntry : ioc.entrySet()) {
            Object value = stringObjectEntry.getValue();
            Class<?> aClass = value.getClass();
            Field[] declaredFields = aClass.getDeclaredFields();
            for (Field declaredField : declaredFields) {
                if(!declaredField.isAnnotationPresent(LagouAutowired.class)){
                    continue;
                }
                //有注解LagouAutowired
                LagouAutowired annotation = declaredField.getAnnotation(LagouAutowired.class);
                String beanName = annotation.value();
                if("".equals(beanName.trim())){
                    beanName = declaredField.getType().getName();
                }
                declaredField.setAccessible(true);
                try {
                    declaredField.set(value, ioc.get(beanName));
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 实例化bean
     */
    private void doInstance() {
        if(classNames.isEmpty()){
            return;
        }
        for (String className : classNames) {
            try {
                Class<?> aClass = Class.forName(className);
                if(aClass.isAnnotationPresent(LagouController.class)){
                    //注解LagouController, id默认取类名首字母小写
                    String lowerFirstSimpleName = lowerFirst(aClass.getSimpleName());
                    Object o = aClass.newInstance();
                    ioc.put(lowerFirstSimpleName, o);
                }else if(aClass.isAnnotationPresent(LagouService.class)){
                    LagouService annotation = aClass.getAnnotation(LagouService.class);
                    String beanName = annotation.value();
                    if (!"".equals(beanName.trim())){
                        ioc.put(beanName, aClass.newInstance());
                    }else{
                        beanName = lowerFirst(aClass.getSimpleName());
                        ioc.put(beanName, aClass.newInstance());
                    }
                    //service层有接口，此时在以接口名为id,放入一份对象到ioc容器中, 便于后期根据接口类型注入
                    Class<?>[] interfaces = aClass.getInterfaces();
                    for (Class<?> anInterface : interfaces) {
                        ioc.put(anInterface.getName(), aClass.newInstance());
                    }
                }else{
                    continue;
                }
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            }
        }
    }

    private String lowerFirst(String simpleName) {
        char[] chars = simpleName.toCharArray();
        if('A' <= chars[0] && chars[0] <= 'Z'){
            chars[0] += 32;
        }
        return String.valueOf(chars);
    }

    /**
     * 扫描类和注解
     * @param scanPackage
     */
    private void doScan(String scanPackage) {
        String packagePath = this.getClass().getClassLoader().getResource("").getPath() + scanPackage.replaceAll("\\.", "/");
        File file = new File(packagePath);
        File[] files = file.listFiles();
        for (File file1 : files) {
            if(file1.isDirectory()){
                //递归
                String fileName = scanPackage + "." + file1.getName();
                doScan(fileName);
            }else if(file1.getName().endsWith(".class")) {
                String className = scanPackage + "." + file1.getName().replaceAll(".class", "");
                classNames.add(className);
            }
        }
    }

    /**
     * 加载配置文件
     * @param contextConfigLocation
     */
    private void doLoadConfig(String contextConfigLocation) {
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(contextConfigLocation);
        try {
            properties.load(resourceAsStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
